var appRoot = "http://localhost:8080/boun"
function JimetFormValidatorObj() { 
 	this.toggleDivId = null;
 	this.formId = null;
 	this.formObj = null;
 	this.postData = null;
 	this.url = appRoot+'/Servlet/FormValidatorAjax';
 	this.errMsg = null;
 	this.resultMsg = null;
 	this.endFunction = null;
 	this.resultObjId = -1;
 	this.resultObjName = null;
 	this.loadingDiv = null;
 	this.disabledFormElements = new Array();
	
 	this.disableAllFormElements = function(objId)
 	{
 		var els = document.getElementById(objId);
 		for(i=0;i<els.length;i++)
 		{
 			if( (els[i].disabled != true) )
 			{
 				els[i].disabled = true;
 				this.disabledFormElements[i] = els[i]; 			
 			}
 		}
 	}

 	this.enableAllFormElements = function(obj)
 	{
 		var els = obj;
 		for(i=0;i<els.length;i++)
 			if(els[i]&&els[i]!=null)
 				els[i].disabled = false;
 	}
 			
 	this.init = function(formId,divId){
		if (!document.getElementById(formId)){
			this.errMsg = 'Not a valid form Id';
			return false;
		}
		
		this.formId = formId;
		this.toggleDivId = divId;
		this.disabledFormElements = new Array();			
		this.formObj = document.getElementById(this.formId);
		
		if ( $('#'+this.toggleDivId+'Loading').length == 0 ){
			$("#"+this.toggleDivId).append("<div id=\""+this.toggleDivId+"Loading\" class=\"loadingDiv\"></div>");
		}
		
		this.formValidationResult = function(result){
			alert('1');	
			if(result=='ajaxError'){
				this.enableAllFormElements(self.disabledFormElements);
				return;
			}
			
			var numOfErrors = 0;

			var qs = new Querystring(decodeURI(result));
			alert('2');	
			if(qs.get('objectId'))
				self.resultObjId = qs.get('objectId'); 
			
			if(qs.get('objectName'))
				self.resultObjName = qs.get('objectName'); 
			
			self.formObj = document.getElementById(qs.get("formId"));
			for(i=0; i<self.formObj.elements.length; i++) 
			{  
				if(document.getElementById(self.formObj.elements[i].id+'ErrMsg')){
					document.getElementById(self.formObj.elements[i].id+'ErrMsg').innerHTML = '';   
					document.getElementById(self.formObj.elements[i].id+'ErrMsg').style.display = 'none';
				}   
			}	

			for(i=0; i<self.formObj.elements.length; i++) 
			{        
				if(document.getElementById(self.formObj.elements[i].id+'ErrMsg') && ( (self.formObj.elements[i].getAttribute('validator')) || (self.formObj.elements[i].id=='it') || (self.formObj.elements[i].id=='combobox3') ) )
				{
					if(qs.get(self.formObj.elements[i].id+"ErrMsg") != 'ok') 
			   		{ 
			   			document.getElementById(self.formObj.elements[i].id+'ErrMsg').style.display = 'block';
				   		document.getElementById(self.formObj.elements[i].id+'ErrMsg').innerHTML = qs.get(self.formObj.elements[i].id+"ErrMsg");        
						numOfErrors++;
					}
				}
			}
				
			if (qs.get("resultErrMsg"))
				numOfErrors++;	

			self.enableAllFormElements(self.disabledFormElements);		
			
			if (self.endFunction)
				self.endFunction(numOfErrors,qs.get("resultErrMsg"),qs.get("resultMsg"),qs.get("formId"));

			this.executeScript(result);			
		};

		loadDiv = $('#'+this.toggleDivId+'Loading');
		var mypos = $('#'+this.toggleDivId).position();
		loadDiv.css({top: mypos.top + "px"});
		loadDiv.height($('#'+this.toggleDivId).height());
		loadDiv.width($('#'+this.toggleDivId).width());
		loadDiv.hide();
		loadDiv.ajaxStart(function() {$(this).show();});
		loadDiv.ajaxStop(function() {$(this).hide();});
			
		return this.formObj;
 	};
 		
 	this.doValidate = function(formId,divId){
		if (!this.init(formId,divId)){
 			alert(this.errMsg);
			return; 	 	 
	 	}

	 	if(this.formObj.id!=formId)
	 	{
			this.formId = formId;
			this.toggleDivId = divId; 			
			this.formObj = document.getElementById(formId);
	 	}

	 	this.formObj = document.getElementById(formId);
		this.disableAllFormElements(this.formId);
	 	formEls = this.formObj.elements;
	 	
	 	var checkboxOrRadioLooped = new Array();
		this.postData = "formId" + "="+ encodeURIComponent(this.formId)+"&";
		this.postData += "action" + "="+ encodeURIComponent(this.formObj.action.value);

		for(i=0; i<formEls.length; i++) 
		{
			if( formEls[i].type == 'text' || formEls[i].type == 'password' || formEls[i].type == 'checkbox' || formEls[i].type == 'radio' || formEls[i].type == 'hidden' || formEls[i].type == 'textarea' || formEls[i].type == 'select-one' || formEls[i].type == 'select-multiple')
			{
				if(formEls[i].type == 'hidden')
				{
			 		this.postData += "&"+formEls[i].id + "="+ encodeURIComponent(formEls[i].value);
			 		this.postData += "&"+formEls[i].id + "HtmlType=" + encodeURIComponent(formEls[i].type);					
				}
				else if( formEls[i].getAttribute('validator') )
				{
					args = formEls[i].getAttribute('validator').split(";");
										
					if(formEls[i].type == 'text' || formEls[i].type == 'password' || formEls[i].type == 'select-one' || formEls[i].type == 'textarea')
				 	{
				 		this.postData += "&"+formEls[i].id + "="+ encodeURIComponent(formEls[i].value);
				 		this.postData += "&"+formEls[i].id + "HtmlType=" + encodeURIComponent(formEls[i].type);
			
				 		this.postData += "&"+formEls[i].id + "Required=" + encodeURIComponent(args[0]);
				 		this.postData += "&"+formEls[i].id + "ValidationType=" + encodeURIComponent(args[1]);
				 		this.postData += "&"+formEls[i].id + "MinLength=" + encodeURIComponent(args[2]);
				 		this.postData += "&"+formEls[i].id + "MaxLength=" + encodeURIComponent(args[3]);
				 		this.postData += "&"+formEls[i].id + "RealLifeName=" + encodeURIComponent(args[4]);
			 		}
			 		else if(formEls[i].type == 'checkbox' || formEls[i].type == 'radio')
			 		{
		 				//inputs = document.getElementsByName(formEls[i].id);
			 			inputs = $('#'+formEls[i].id);
			 			var checkedInputs = $('#'+formEls[i].id+':checked');
			 			var looped = false;
			 			
			 			for(f=0;f<checkboxOrRadioLooped.length;f++)
			 			{
			 				if(formEls[i].id==checkboxOrRadioLooped[f])
			 				{
			 					looped = true;
			 					break;
			 				}
			 			}
			 			
			 			if(!(looped))
			 			{
			 				for(k=0;k<inputs.length;k++)
			 				{	
			 					if(inputs[k].checked)
			 					{
							 		checkedInputs.push(inputs[k]);
							 		checkboxOrRadioLooped.push(formEls[i].id);
			 					}
			 				}

			 				if(checkedInputs.length>1)
			 				{
			 					for(k=0;k<checkedInputs.length;k++)
			 					{
							 		this.postData += "&"+formEls[i].id + "="+ encodeURIComponent(checkedInputs[k].value);
							 		this.postData += "&"+formEls[i].id + "HtmlType=" + encodeURIComponent(checkedInputs[k].type);
							 		this.postData += "&"+formEls[i].id + "Required=" + encodeURIComponent(args[0]);
							 		this.postData += "&"+formEls[i].id + "ValidationType=" + encodeURIComponent(args[1]);
							 		this.postData += "&"+formEls[i].id + "MinLength=" + encodeURIComponent(args[2]);
							 		this.postData += "&"+formEls[i].id + "MaxLength=" + encodeURIComponent(args[3]);
							 		this.postData += "&"+formEls[i].id + "RealLifeName=" + encodeURIComponent(args[4]);			 				
							 	}
			 				}
			 				else 
				 			{
		 						var st = +checkedInputs.length==1?checkedInputs[0].value:'';
						 		this.postData += "&"+formEls[i].id + "="+st;
								this.postData += "&"+formEls[i].id + "HtmlType=text";
						 		this.postData += "&"+formEls[i].id + "Required=" + encodeURIComponent(args[0]);
						 		this.postData += "&"+formEls[i].id + "ValidationType=" + encodeURIComponent(args[1]);
						 		this.postData += "&"+formEls[i].id + "MinLength=" + encodeURIComponent(args[2]);
						 		this.postData += "&"+formEls[i].id + "MaxLength=" + encodeURIComponent(args[3]);
						 		this.postData += "&"+formEls[i].id + "RealLifeName=" + encodeURIComponent(args[4]);
						 		checkboxOrRadioLooped.push(formEls[i].id);
				 			}
			 			}
			 		}
			 		else if(formEls[i].type == 'select-multiple')
			 		{
			 			var multiOptions = formEls[i].options;

			 			if(formEls[i].id.match("SelectedValues"+"$")=="SelectedValues")
			 			{
			 				for(k=0;k<multiOptions.length;k++)
			 					multiOptions[k].selected = true;
			 			}

			 			var selectedMultiples = new Array();
			 			for(k=0;k<multiOptions.length;k++)
			 			{
			 				if(multiOptions[k].selected)
			 					selectedMultiples.push(multiOptions[k]);
			 			}
			 			
			 			if(!(selectedMultiples.length>1))
			 			{			
	 						var st = selectedMultiples.length==1?selectedMultiples[0].value:'';
					 		this.postData += "&"+formEls[i].id + "="+st;
					 		this.postData += "&"+formEls[i].id + "HtmlType=text";
					 		this.postData += "&"+formEls[i].id + "Required=" + encodeURIComponent(args[0]);
					 		this.postData += "&"+formEls[i].id + "ValidationType=" + encodeURIComponent(args[1]);
					 		this.postData += "&"+formEls[i].id + "MinLength=" + encodeURIComponent(args[2]);
					 		this.postData += "&"+formEls[i].id + "MaxLength=" + encodeURIComponent(args[3]);
					 		this.postData += "&"+formEls[i].id + "RealLifeName=" + encodeURIComponent(args[4]);			 			
			 			}
			 			else
			 			{
			 				for(k=0;k<selectedMultiples.length;k++) 
			 				{
						 		this.postData += "&"+formEls[i].id + "="+ encodeURIComponent(selectedMultiples[k].value);
						 		this.postData += "&"+formEls[i].id + "HtmlType=" + encodeURIComponent(formEls[i].type);
						 		this.postData += "&"+formEls[i].id + "Required=" + encodeURIComponent(args[0]);
						 		this.postData += "&"+formEls[i].id + "ValidationType=" + encodeURIComponent(args[1]);
						 		this.postData += "&"+formEls[i].id + "MinLength=" + encodeURIComponent(args[2]);
						 		this.postData += "&"+formEls[i].id + "MaxLength=" + encodeURIComponent(args[3]);
						 		this.postData += "&"+formEls[i].id + "RealLifeName=" + encodeURIComponent(args[4]);			 			
			 				}
			 			}
			 		}			 		
				}
			}
		}

		var self = this;	
		$.ajax({
			type: "POST",
			data: this.postData,
			contentType: "application/x-www-form-urlencoded; charset=utf-8",	
			url: this.url,
		  	success: function(response){
				formValidationResult(self , response)
		  	},
		  	error: function(jqXHR, textStatus, errorThrown) {
		  	    alert(jqXHR.status);
		  	    alert(textStatus);
		  	    alert(errorThrown);
		  	}	
		});		
 	};


	this.executeScript = function(content) 
	{
	    var src = new RegExp('<script.*?src=".*?"');
	    var repl = new RegExp('<script.*?src="');
	    var matches = src.exec(content);
	    repl = new RegExp('<script.*?src=".*?".*?</script>');
	    content = content.replace(repl, '');

	    // inline scriptler i?in
	    // script commentlerini kald?r
	    repl = new RegExp('//.*?$', 'gm');
	    content = content.replace(repl, '\n');

	    // enterlar? clean
	    repl = new RegExp('[\n\r]', 'g');
	    content = content.replace(repl, ' ');
	
	    //<script> i?indeki her?eyi match et
	    src = new RegExp('<script.*?</script>', 'g');
	    matches = content.match(src);


	    if (matches != null)
	    {
	        for (i = 0; i < matches.length; i++)
	        {
	            // ba?taki tag? kald?r
	            var repl = new RegExp('<script.*?>', 'gm');
	            var script = matches[i].replace(repl, '');
	
	            // sondaki tag? kald?r
	            repl = new RegExp('</script>', 'gm');
	            script = script.replace(repl, '');
	
	            // comutlar? ?al??t?r
	            setTimeout(script, 250);
	        }
	    }
	} 	
	
	this.setEndFunction = function(endFunc){
		this.endFunction = endFunc;
	};
}

function formValidationResult ( jobj , result){

	if(result=='ajaxError'){
		jobj.enableAllFormElements(jobj.disabledFormElements);
		return;
	}
	
	var numOfErrors = 0;

	var qs = new Querystring(decodeURI(result));

	if(qs.get('objectId'))
		jobj.resultObjId = qs.get('objectId'); 
	
	if(qs.get('objectName'))
		jobj.resultObjName = qs.get('objectName'); 
	
	jobj.formObj = document.getElementById(qs.get("formId"));
	for(i=0; i<jobj.formObj.elements.length; i++) 
	{  
		if(document.getElementById(jobj.formObj.elements[i].id+'ErrMsg')){
			document.getElementById(jobj.formObj.elements[i].id+'ErrMsg').innerHTML = '';   
			document.getElementById(jobj.formObj.elements[i].id+'ErrMsg').style.display = 'none';
		}   
	}	

	for(i=0; i<jobj.formObj.elements.length; i++) 
	{        
		if(document.getElementById(jobj.formObj.elements[i].id+'ErrMsg') && ( (jobj.formObj.elements[i].getAttribute('validator')) || (jobj.formObj.elements[i].id=='it') || (jobj.formObj.elements[i].id=='combobox3') ) )
		{
			if(qs.get(jobj.formObj.elements[i].id+"ErrMsg") != 'ok') 
	   		{ 
	   			document.getElementById(jobj.formObj.elements[i].id+'ErrMsg').style.display = 'block';
		   		document.getElementById(jobj.formObj.elements[i].id+'ErrMsg').innerHTML = qs.get(jobj.formObj.elements[i].id+"ErrMsg");        
				numOfErrors++;
			}
		}
	}
		
	if (qs.get("resultErrMsg"))
		numOfErrors++;	

	jobj.enableAllFormElements(jobj.disabledFormElements);		
	
	if (jobj.endFunction)
		jobj.endFunction(numOfErrors,qs.get("resultErrMsg"),qs.get("resultMsg"),qs.get("formId"));

	jobj.executeScript(result);			
};
